<template>
    <div>
        <!-- <div class="super_left" v-if="isShow"></div> -->
        <!-- //id="player": 渲染3D场景窗口的Dom节点; 不要在里面加任何自定义开发的元素, 特别是video; 不要使用VUE自身的 v-show; -->
        <div id="player" style="display:none;"></div>
        <!-- <div class="super_right" v-if="isShow"></div> -->
    </div>
</template>

<script>
//引入SuperAPI.js
// import cloudRenderer from "superapi-51world";
import { GETNOBASE } from 'api';
import { currentPOST } from 'api/modules';
import cloudRenderer from "51superapi"
import UtilVar from "@/config/UtilVar";
import { bd09ToWgs84 } from "@/utils/map/mapUtils";

export default {
    name: "SuperBackground",
    data() {
        return {
            cloudRender: null,
            markers: [],
        }
    },
    computed: {
        sbtxSwiper() {
            return this.$store.state.setting.sbtxSwiper
        },
        pageNo() {
            return this.$store.state.setting.pageNo
        },
        isShow() {
            const pageNo = this.$store.state.setting.pageNo
            if (pageNo === 0 || pageNo === 2 || pageNo === 3) { //运输车辆
                return true
            }
            return false
            // },
            // currentGuji() {
            //     return this.$store.state.setting.currentGuji;
        }
    },
    watch: {
        pageNo: {
            handler(newVal, oldVal) {
                this.RemoveAllCovering();
                if (newVal === 2) {
                    this.AddGeoRange();
                } else if (newVal == 3) {
                    // this.AddGeoRange();
                } else if (newVal == 0) {
                    // this.AddGeoRange();
                }
            },
            // immediate: true
        },
        sbtxSwiper(val) {
            if (val) {
                this.removeSuperService() //关闭云渲染, 释放资源
                this.createSuperService(UtilVar.superUrl);
            } else {
                this.removeSuperService() //关闭云渲染, 释放资源
                this.createSuperService(UtilVar.superPrivateUrl);
            }
        },
        // currentGuji(val) {
        //     if (val.actionName === 'AddPath') {
        //         this.RemoveAllCovering();
        //         this.AddPath(val);
        //     }
        // }
    },
    created() {
        this.removeSuperService() //关闭云渲染, 释放资源
        // this.createSuperService(UtilVar.superPrivateUrl);
        this.createSuperService(UtilVar.superUrl);
    },
    destroyed() {
        this.removeSuperService() //关闭云渲染, 释放资源
    },
    methods: {
        async createSuperService(url) {
            const app = new cloudRenderer("player");
            const myStyle = this.isShow ? 'top: 0px' : 'top: -9000px'; // this.pageNo == 0 ? 1800 : 4500;// 4500 2800;
            const startRenderConfig = {
                url, //[必须] 云渲染服务地址; 8889:固定端口
                "order": UtilVar.superToken, //[必须] 渲染口令; 在云渲染客户端上获得
                "resolution": [4500, 1080], //[可选] 设置渲染场景像素分辨率
                "nodestyle": `position:absolute;border-radius: 20px;${myStyle};`, //[可选] 设置渲染场景容器DOM节点样式, 与设置渲染场景像素分辨率配对使用
                "keyboard": "keyboardnofn", //[可选] 初始建盘事件, 开启wasd方向键 [选项: keyboard/keyboardnofn; 详见注册键盘事件]
                "setlogmode": false, //[可选] 开启/关闭SuperAPI调用日志, 默认false
            }
            try {
                await app.startRender(startRenderConfig).then((el) => {
                    // console.log("打印信息", el)

                    // 事件注册；事件监听处理器函数, 接收所有从云渲染返回的事件, 数据等信息
                    app.RegisterCloudResponse(this.handleResponseFunction);
                })
            } catch (error) {
                console.error("error:", error)
            }
            this.cloudRender = app;
        },
        removeSuperService() {
            if (this.cloudRender) {
                this.cloudRender.SuperAPI("StopRenderCloud") //关闭云渲染, 释放资源
                this.cloudRender = null;
            }
        },
        handleResponseFunction(response) {
            // console.log('收到的事件 response: ' + response);
            const jsonObject = typeof response === 'object' ? JSON.parse(JSON.stringify(response)) : JSON.parse(response)
            switch (jsonObject.func_name) {
                case "beginPlay":
                    // 云渲染连接成功 do Something
                    break;
                case "APIAlready":
                    // 3D世界加载完成 do Something

                    this.loadCameraInfo();
                    // this.loadSuperMapBg(); // 切换水晶体底板
                    break;
                case "OnPOIClick":
                    // console.log("🚀 ~ this.cloudRender.SuperAPI ~ OnPOIClick:", jsonObject.args)
                    this.handlerPOIClick(jsonObject.args)
                    break;
                case "OnAddPathSuccess":
                    // 添加路径成功 do Something
                    break;
                case "OnAddPathFailed":
                    // 添加路径失败 do Something
                    break;
                case "OnUpdatePathCoordSuccess":
                    // 更新路径数据点成功 do Something
                    break;
                case "OnUpdatePathCoordFailed":
                    // 更新路径数据点失败 do Something
                    break;
                case "OnFocusPathEnd":
                    // 聚焦路径结束 do Something
                    break;

                case "OnPathClick":
                    // 点击路径 do Something
                    break;
                case "OnSuperAPI_Error_Catch":
                    // 错误捕捉 do Something
                    // "args": {
                    //   "error_type": "SuperAPI JSon Body Field Error",
                    //   "error_information": "id"
                    // }
                    break;
                //更多func_name类型 回调通知, 详见各API事件
            }
            return response;
        },
        loadSuperMapBg() {
            let jsondata = {
                "layer_name": "all", //层名称;  "all" 所有layer
                "bcrystal": true, //true:显示; false:隐藏
                "color": "0f2d60" //颜色(HEX颜色值) 0f2d60
            }
            if (this.cloudRender) {
                this.cloudRender.SuperAPI('CrystalAESLayer', jsondata, (_back) => {
                    console.log("🚀 ~ this.cloudRender.SuperAPI ~ CrystalAESLayer:", _back)
                });
            }
        },
        loadCameraInfo() {
            let jsonData = {
                coord_type: 0, //坐标类型(0:经纬度坐标, 1:cad坐标)
                cad_mapkey: "default", //CAD基准点Key值, 项目中约定
                coord_z: "65.16", //海拔高度(单位:米)
                // center_coord: "118.245515, 35.120025", //中心点的坐标 大集
                center_coord: "118.24016299614458, 35.11625261402105", //中心点的坐标 "顺和天源智慧物流园"
                arm_distance: 2200,//800 1200, //镜头距中心点距离(单位:米)
                pitch: 30, //镜头俯仰角(0 ~ 89)
                yaw: 1, // 1, //镜头偏航角(0正北, 0 ~ 359)
                fly: true, //true, false
                // true: 飞行动画
                // false: 立刻跳转过去(瞬移)
            };

            this.cloudRender.SuperAPI("SetCameraInfo", jsonData, (_back) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ SetCameraInfo:", _back)
            });
        },
        // 添加POI功能
        AddPOI1(subobj = []) {
            //常量
            let obj = {
                // "type": "default",
                // "coord_type": 0,
                // "cad_mapkey": "",
                "coord_z": 1,
                "coord_z_type": 0,
                "always_show_label": true,
                "show_label_range": "0,6000",
                // "umg_type": "default",
                // "sort_order": true,
                // "animation_type": "bounce",
                // "duration_time": .7,
                "state": "state_1",
                marker: {
                    size: "216,282",// Marker大小(宽，高 单位:像素)
                    images: [
                        {
                            define_state: "state_1",
                            normal_url: "path:/UserData/miaoq.png",
                            activate_url: "",//hover,active时图片url地址
                        }
                    ]
                }
            }

            // //变量
            // let subobj = [
            //     {
            //         "id": "poi_id_01",
            //         "label": "标题文本0",
            //         "coord": "113.99751138,22.57122103",
            //     },
            //     {
            //         "id": "poi_id_02",
            //         "label": "标题文本1",
            //         "coord": "114.00372035,22.57670472",
            //     },
            // ]

            this.markers = subobj;
            this.cloudRender.SuperAPI("AddCustomPOI", obj, subobj, (status) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ AddCustomPOI:", status)
            })
        },
        // 添加POI功能
        AddPOI(subobj = []) {
            //常量
            let obj = {
                "type": "default",
                "coord_type": 0,
                "cad_mapkey": "",
                "coord_z": 1,
                "coord_z_type": 0,
                "always_show_label": true,
                "show_label_range": "0,6000",
                "umg_type": "default",
                "sort_order": true,
                "animation_type": "bounce",
                "duration_time": .7
            }

            // //变量
            // let subobj = [
            //     {
            //         "id": "poi_id_01",
            //         "label": "标题文本0",
            //         "coord": "113.99751138,22.57122103",
            //     },
            //     {
            //         "id": "poi_id_02",
            //         "label": "标题文本1",
            //         "coord": "114.00372035,22.57670472",
            //     },
            // ]

            this.markers = subobj;
            this.cloudRender.SuperAPI("AddPOI", obj, subobj, (status) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ AddPOI:", status)
            })
        },
        RemoveAllCovering() {
            let jsondata = {
                "covering_type": ["poi", "range"]   //覆盖物类型, 详见下表
            }
            this.cloudRender.SuperAPI("RemoveAllCovering", jsondata, (status) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ RemoveAllCovering:", status)
            })
        },
        async AddGeoRange() {
            let jsondata = {
                "id": "range_id",
                "coord_type": 0,                  //坐标类型(0:经纬度坐标, 1:cad坐标)
                "cad_mapkey": "",                 //CAD基准点Key值, 项目中约定
                "coord_z": 0,                     //高度(单位:米)
                "coord_z_type": 0,                //坐标高度类型(0:相对3D世界表面；1:相对3D世界地面；2:相对3D世界海拔; 注:cad坐标无效)
                "type": "wave",                   //样式类型; 注①
                "color": "1890FF88",              //轮廓颜色(HEXA颜色值)
                "range_height": 100,               //围栏高度(单位:米)
                "stroke_weight": 10,              //底部轮廓线宽度(单位:米; 注: 区域中含有内环"inner_points"时无效)
                "fill_area": "none",              //底部区域填充类型; 注②
                "id_field_name": "id",            //指定geojson中的id字段

                // "coord_type": 0,                          //坐标类型(0:经纬度坐标, 1:cad坐标)
                // "cad_mapkey": "",                         //CAD基准点Key值, 项目中约定
                // "color": "cbba89",                        //高亮区域颜色(HEX颜色, 默认为原色高亮)
                // "exterior_color": "00ffff",               //外部颜色(HEX颜色)
                // "exterior_outline_color": "ff00ff",       //外部勾边颜色(HEX颜色)
                // "exterior_transparency": 50,              //透明度(0, 100)
                // "exterior_saturation": 0,                 //饱和度(-100, 100)
                // "exterior_brightness": 0,                 //亮度(-100, 100)
                // "exterior_contrast": 0,                   //对比度(-100, 100)
                //支持json或文件形式、二选一
                // "geojson": "http://superapi.51aes.com/doc-static/images/static/yangli/range.geojson",
            }
            // const geojson = await GETNOBASE(`./map-geojson/yanqu.json`).then((res) => res);

            const objIds = []
            const geojson = await currentPOST(`mapCityMakers`).then((res) => {
                const result = {
                    type: "FeatureCollection",
                    features: []
                }
                const dataList = res.data.map((item, idx) => {
                    const centerPoint = JSON.parse(item.centerPoint);
                    const coords = JSON.parse(item.lonlats)[0].split(';').map(p => {
                        const [x, y] = p.split(",")
                        // return [parseFloat(x), parseFloat(y)]
                        return bd09ToWgs84(parseFloat(x), parseFloat(y))
                    });
                    let [wgs84Lng, wgs84Lat] = bd09ToWgs84(parseFloat(centerPoint.lng), parseFloat(centerPoint.lat));
                    objIds.push({
                        id: item.fenceId,
                        label: item.fenceName,
                        coord: `${wgs84Lng},${wgs84Lat}`
                    })
                    return {
                        type: 'Feature',
                        id: 100000 + idx,
                        properties: {
                            "_draw_type": "fill",
                            "adcode": item.fenceId,
                            centerPoint
                        },
                        name: item.fenceName,
                        geometry: {
                            "type": "Polygon",
                            "coordinates": [coords]
                        }
                    }
                });

                console.log("🚀 ~ mapCityMakers ~ dataList:", dataList)
                result.features = dataList;
                return result;
            });
            jsondata.geojson = geojson;
            this.cloudRender.SuperAPI("AddGeoRange", jsondata, (status) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ AddGeoRange:", status)


                // this.SetCameraToMove(100000); // 100000~100012
            })
            this.AddPOI(objIds);
        },
        ShowAndHideGeoRange(visible = true) {
            if (this.cloudRender) {
                let jsondata = {
                    "covering_type": ["poi", "range"],    //覆盖物类型, 详见下表
                    "bshow": visible              //true:显示; false:隐藏
                }
                this.cloudRender.SuperAPI("ShowHideAllCovering", jsondata, (status) => {
                    console.log("🚀 ~ this.cloudRender.SuperAPI ~ ShowHideAllCovering:", status)
                })

            }
        },
        AddPath(args) {
            let jsondata = {
                "id": args.carNo,
                "advancedSetting": {
                    "smoothnessOfCorners": "extremelyHigh"  //设置路径边角的平滑度(extremelyHigh:极高; high:高; middle:中; low:低;)
                },
                "coord_type": 0,                    //坐标类型(0:经纬度坐标, 1:cad坐标)
                "coord_z_type": 0,                  //坐标高度类型(0:相对3D世界表面；1:相对3D世界地面；2:相对3D世界海拔; 注:cad坐标无效)
                "cad_mapkey": "",                   //CAD基准点Key值, 项目中约定
                "type": "arrow",                    //样式类型; 注①
                "color": "ff0000",                  //颜色(HEX颜色值, 空值即透明; railway类型无效, 默认黑白色)
                "pass_color": "ffff00",             //覆盖物移动经过路径颜色(HEX颜色值)
                "width": 10,                        //宽度(单位:米, 圆柱直径或方柱边长；当类型为“adaptive_solid”，含义为倍率)
                "speedRate": 1,                      //流动特效的移动倍率,仅针对部分类型有效（arrow,arrow_dot,arrow_dashed,brimless_arrow,scan_line,scan_line_solid）
                "points": args.points.map(item => ({ "coord": item.coord, "coord_z": item.coord_z })),
                // "points": [
                //     {
                //         "coord": "134.55,34.577",   //路径坐标点 lng,lat
                //         "coord_z": 1                //高度(单位:米)
                //     },
                //     {
                //         "coord": "134.59,33.577",
                //         "coord_z": 2
                //     }
                // ]
            }
            console.log("🚀 ~ AddPath ~ jsondata:", jsondata)
            if (this.cloudRender) {
                this.cloudRender.SuperAPI("AddPath", jsondata, (status) => {
                    console.log("🚀 ~ this.cloudRender.SuperAPI ~ AddPath:", status)
                })
            }
        },

        ResetCameraInfo(center_coord) {
            let jsondata = {
                "coord_type": 0,                                 //坐标类型(0:经纬度坐标, 1:cad坐标)
                "cad_mapkey": "",                                //CAD基准点Key值, 项目中约定
                "coord_z": "2.06",                               //海拔高度(单位:米)
                "center_coord": center_coord,           //中心点的坐标 lng,lat
                "arm_distance": 1000,                            //镜头距中心点距离(单位:米)
                "pitch": 30,                                     //镜头俯仰角(5~89)
                "yaw": 0,                                        //镜头偏航角(0正北, 0~359)
                "fly": true                                      //true: 飞行动画(有一个短暂飞行动画,并按照arm_distance,pitch,yaw设置镜头);
                //false: 立刻跳转过去(瞬移)
            }
            this.cloudRender.SuperAPI("ResetCameraInfo", jsondata, (status) => {
                console.log("🚀 ~ this.cloudRender.SuperAPI ~ cloudRender:", status)
            })
        },
        handlerPOIClick(args) {
            // console.log("🚀 ~ handlerPOIClick ~ args:", args, this.markers)
            const curr = this.markers.find(item => item.id == args.id)
            console.log("🚀 ~ handlerPOIClick ~ curr:", curr)
            if (curr) {
                this.$store.state.setting.currentMarker = curr;
                // this.ResetCameraInfo(curr.coord);
            }
        }
    }
}
</script>

<style lang="less" scoped>
.super_left {
    position: absolute;
    top: 0;
    z-index: 1;
    width: 200px;
    height: 1080px;
    background: linear-gradient(to right, #0f2d60, transparent);
}

.super_right {
    position: absolute;
    top: 0;
    left: 1600px;
    z-index: 1;
    width: 200px;
    height: 1080px;
    background: linear-gradient(to left, #152f5d, transparent);
}
</style>